package proxys

import (
	"crypto/tls"
	"fmt"
	"net/http"
	"net/http/httputil"
	"net/url"
)

var pathProxys = map[string]*httputil.ReverseProxy{}
var patternProxys = map[string]*httputil.ReverseProxy{}

var transport *http.Transport

func InitReverseProxy() {
	transport = http.DefaultTransport.(*http.Transport).Clone()
	transport.MaxIdleConns = 100
	transport.MaxConnsPerHost = 100
	transport.MaxIdleConnsPerHost = 100
	transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
}

func GetOrCreatePathProxy(scheme, host, path string) *httputil.ReverseProxy {
	key := fmt.Sprintf("%s-%s-%s", scheme, host, path)
	proxy, ok := pathProxys[key]
	if ok {
		return proxy
	}

	director := func(req *http.Request) {
		req.URL.Scheme = scheme
		req.URL.Host = host
		req.URL.Path = path
	}
	proxy = &httputil.ReverseProxy{Director: director, Transport: transport}
	pathProxys[key] = proxy
	return proxy
}

func GetOrCreatePatternProxy(url *url.URL) *httputil.ReverseProxy {
	proxy, ok := patternProxys[url.String()]
	fmt.Println(proxy, ok)
	if ok {
		return proxy
	}
	director := func(req *http.Request) {
		req.URL = url
	}
	proxy = &httputil.ReverseProxy{Director: director, Transport: transport}
	patternProxys[url.String()] = proxy
	return proxy
}
